//
//  CNBBSSectionViewController.m
//  CsdnPlus
//
//  Created by 孟瑞瑞 on 2018/5/31.
//  Copyright © 2018年 CSDN. All rights reserved.
//

#import "CNBBSSectionViewController.h"
#import "CNBBSChannelItem.h"
#import "CNBBSSectionHeader.h"
#import "CNBBSForumListViewModel.h"
#import "CNBBSSectionFlowLayout.h"
#import "CNBBSFavoriteViewModel.h"
#import <CNBaseViewTool/CNNoDataView.h>
#import <CNBaseViewTool/UIView+CNEmpty.h>
#import <CNBaseTool/CNCategoryHeader.h>


@interface CNBBSSectionViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,CNBBSSectionFlowLayoutDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) CNBBSForumListViewModel *forumVM;

@property (nonatomic, strong) CNBBSFavoriteViewModel *favoriteVM;

@property (nonatomic, strong) CNNoDataView *noDataView;
@property (nonatomic, strong) CNNoDataView *noNetworkView;

@end

@implementation CNBBSSectionViewController

-(CNBBSForumListViewModel *)forumVM
{
    if (!_forumVM) {
        _forumVM = [[CNBBSForumListViewModel alloc]init];
    }
    return _forumVM;
}

-(CNBBSFavoriteViewModel *)favoriteVM
{
    if (!_favoriteVM) {
        _favoriteVM = [[CNBBSFavoriteViewModel alloc]init];
    }
    return _favoriteVM;
}

- (CNNoDataView *)noDataView{
    if (!_noDataView) {
        _noDataView = [CNNoDataView diyEmptyView];
    }
    if ([CNThemesManager isNight])
    {
        _noDataView.imageStr = @"noData_b";
    }
    else
    {
        _noDataView.imageStr = @"noData_w";
    }
    return _noDataView;
}
- (CNNoDataView *)noNetworkView{
    if (!_noNetworkView) {
        _noNetworkView = [CNNoDataView diyEmptyActionViewWithTarget:self action:@selector(headerRefresh)];
    }
    if ([CNThemesManager isNight])
    {
        _noNetworkView.imageStr = @"noNetwork_b";
    }
    else
    {
        _noNetworkView.imageStr = @"noNetwork_w";
    }
    return _noNetworkView;
}

-(void)buildUI
{
    
    self.view.theme_backgroundColor = pageBGColorPicker;
    
    CNBBSSectionFlowLayout *flowLayout = [[CNBBSSectionFlowLayout alloc] init];
    flowLayout.rowHeight = 40;
    flowLayout.delegate = self;
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - 64) collectionViewLayout:flowLayout];
    _collectionView.showsHorizontalScrollIndicator = false;
    
    _collectionView.backgroundColor = [UIColor clearColor];
    [_collectionView registerClass:[CNBBSChannelItem class] forCellWithReuseIdentifier:@"CNChannelItem"];
    [_collectionView registerClass:[CNBBSSectionHeader class]
        forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"CNBBSSectionHeader"];
    [_collectionView registerClass:[UICollectionReusableView class]
        forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"CNBBSSectionFooter"];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [self.view addSubview:_collectionView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self buildUI];
    [self refreshData];
    self.navigationItem.title = @"全部版块";
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.view.theme_backgroundColor = pageBGColorPicker;
    [self addBlackItemToVC];
    
//    if ([CNThemesManager isNight])
//    {
//        //切换背景为夜间颜色
//        [self wr_setNavBarBarTintColor:slideBarNightTextColor];
//        [self wr_setNavBarTitleColor:navigationBarNightTitleColor];
//        [self wr_setStatusBarStyle:UIStatusBarStyleLightContent];
//    }
//    else
//    {
//        //切换背景为白天颜色
//        [self wr_setNavBarBarTintColor:slideBarTextColor];
//        [self wr_setNavBarTitleColor:navigationBarTitleColor];
//        [self wr_setStatusBarStyle:UIStatusBarStyleDefault];
//    }
    
    //添加分割线
//    UIView *lineView = [[UIView alloc]init];
//    lineView.theme_backgroundColor = bbsSectionLineColorPicker;
//    [self.view addSubview:lineView];
//    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.mas_equalTo(0);
//        make.top.mas_equalTo(0);
//        make.height.mas_equalTo(0.5);
//    }];
//    lineView.layer.zPosition = 10;
}



-(void)headerRefresh
{
    [self refreshData];
}

#pragma mark - 获取数据
//刷新数据
- (void)refreshData
{
    [self.collectionView cn_startLoading];
    [self.forumVM getDataFromNetCompleteHandle:^(NSError *error) {
        
        if (!error)
        {
            if (self.forumVM.code == 200) {
                //AF的回调 是在主线程中
                [self.collectionView reloadData];
                self.collectionView.cn_emptyView = self.noDataView;
            }
            else
            {
                [self showErrorMsg:@"加载失败，请稍后再试"];
            }
            
        }else
        {
            [self showError:error];;
            self.collectionView.cn_emptyView = self.noNetworkView;
        }
        //占位图调用时机
        [self.collectionView cn_endLoading];
    }];
}

- (void)addBlackItemToVC
{
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn theme_setImage:navBackImage forState:UIControlStateNormal]; //设置自定义返回图片
    [btn theme_setImage:navBackImage forState:UIControlStateHighlighted]; //设置自定义返回图片
    [btn setTitle:@"" forState:UIControlStateNormal];
    [btn setImageEdgeInsets:UIEdgeInsetsMake(0, -20, 0, 0)];  //调整按钮内图片的布局
    [btn setEnlargeEdge:15];
    btn.frame = CGRectMake(0, 0, 30, 44);
    
    @weakify(self);
    [btn bk_addEventHandler:^(id sender) {
        
        @strongify(self);
        [self.navigationController popViewControllerAnimated:YES];
        self.block();
    } forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *menuItem = [[UIBarButtonItem alloc]initWithCustomView:btn];
    //使用弹簧控件缩小菜单按钮和边缘距离
    UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    UIBarButtonItem *spaceItemRight = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    //spaceItem.width = -12;
    //spaceItemRight.width = 40;
    self.navigationItem.leftBarButtonItems = @[spaceItem,menuItem,spaceItemRight];
}

#pragma mark -
#pragma mark CollectionViewDelegate&DataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [self.forumVM childRowNumberForRow:section];
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.forumVM.rowNumber;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if([kind isEqualToString:UICollectionElementKindSectionHeader])
    {
        CNBBSSectionHeader *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"CNBBSSectionHeader" forIndexPath:indexPath];
        CGRect itemFrame = [[self.forumVM nameForRow:indexPath.section] boundingRectWithSize:CGSizeMake(0, 20) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:17]} context:nil];
        
        CGFloat width = itemFrame.size.width + 20;
        
        [headerView.textBtn mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(width);
        }];
        
        headerView.title = [self.forumVM nameForRow:indexPath.section];
        headerView.isFixed = [self.forumVM isFavoritedForRow:indexPath.section];
        headerView.imageView.hidden = YES;
        headerView.imageBgView.alpha = 0;
        [headerView.textBtn addTarget:self action:@selector(headerClickWithBtn:) forControlEvents:UIControlEventTouchUpInside];
        headerView.textBtn.tag = indexPath.section;
        return headerView;
    }
    else
    {
        UICollectionReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"CNBBSSectionFooter" forIndexPath:indexPath];
        reusableView.theme_backgroundColor = bbsSectionLineColorPicker;
        return reusableView;
    }
}

- (void)headerClickWithBtn:(UIButton *)button
{
    
    [self.favoriteVM getBBSFavoriteWithForumId:[self.forumVM urlnameForRow:button.tag] AndIsFavorite:[self.forumVM isFavoritedForRow:button.tag] CompletionHandle:^(NSError *error) {
        if (!error) {
            if (self.favoriteVM.code == 200)
            {
                if (self.favoriteVM.success) {
                    DDLogDebug(@"感兴趣或者不感兴趣成功");
                    [self.forumVM setIsFavorited:![self.forumVM isFavoritedForRow:button.tag] InForRow:button.tag];
                    
                    [self.collectionView reloadData];
                }
            }
            else if (self.favoriteVM.code == 401)
            {
                //未登录
                [CNRouteTool routeUrl:[CNRoutePath appUrlWithRoutePath:CNLoginQuickRoute] navigationVc:self.navigationController refer:@"" trackingCode:@"" urlParams:@{} vipReferrer:@"" exts:@{}]; 
            }
            
        }
    }];
}

- (void)collectionView:(UICollectionView *)collectionView willDisplaySupplementaryView:(UICollectionReusableView *)view forElementKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath
{
    if (@available(iOS 11.0, *)) {
        
       view.layer.zPosition = 0;
        
    }
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* cellId = @"CNChannelItem";
    CNBBSChannelItem* item = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
    item.title = [self.forumVM nameForRow:indexPath.row AndSection:indexPath.section];
    item.isFixed = [self.forumVM isFavoritedForRow:indexPath.row AndSection:indexPath.section];
    item.imageView.hidden = YES;
    item.imageBgView.alpha = 0;
    
//    if (indexPath.section == 0)
//    {
//        DDLogDebug(@"%@",item.title);
//        item.imageView.image = [UIImage imageNamed:@"delete"];
//    }
//    else
//    {
//        DDLogDebug(@"%@",item.title);
//        item.imageView.image = [UIImage imageNamed:@"add_channel"];
//    }
    return  item;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    [self.favoriteVM getBBSFavoriteWithForumId:[self.forumVM urlnameForRow:indexPath.row AndSection:indexPath.section] AndIsFavorite:[self.forumVM isFavoritedForRow:indexPath.row AndSection:indexPath.section] CompletionHandle:^(NSError *error) {
        if (!error) {
            if (self.favoriteVM.code == 200)
            {
                if (self.favoriteVM.success) {
                    DDLogDebug(@"感兴趣或者不感兴趣成功");
                    [self.forumVM setIsFavorited:![self.forumVM isFavoritedForRow:indexPath.row AndSection:indexPath.section] InForRow:indexPath.row AndSection:indexPath.section];
                    
                    [collectionView reloadData];
                }
            }
            else if (self.favoriteVM.code == 401)
            {
             [CNRouteTool routeUrl:[CNRoutePath appUrlWithRoutePath:CNLoginQuickRoute] navigationVc:self.navigationController refer:@"" trackingCode:@"" urlParams:@{} vipReferrer:@"" exts:@{}];
            }
            
        }
    }];
    
    
}


#pragma mark - CNBBSSectionFlowLayoutDelegate
- (CGFloat)waterFlowLayout:(CNBBSSectionFlowLayout *)layout widthAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *content = [self.forumVM nameForRow:indexPath.row AndSection:indexPath.section];
    CGRect itemFrame = [content boundingRectWithSize:CGSizeMake(0, 20) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:17]} context:nil];
    
    CGFloat width = itemFrame.size.width + 4;
    return width;
}

@end
